/*+==================================================
	* Copyright 2012 TVU networks Ltd. All rights reserved
	* For internal members in TVU networks only.
	*
	* FileName: XDaoImpl.java
	*
	* Purpose: The class provides the implementation for the XDaoImpl class  for project tvupack grid Server
	*
	* Author: frankzhou (frankzhou@tvunetworks.com)
	* History: frankzhou created on 08/03, 2012,
	* created with: Eclipse
	=================================================+*/
package com.tvunetworks.center.device.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Date;

/**
 * String Utility Class This is used to encode passwords programmatically
 *
 * <p>
 * <a h ref="StringUtil.java.html"><i>View Source</i></a>
 * </p>
 *
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
 */
@Slf4j
public class StringUtil {

	// ~ Static fields/initializers
	// =============================================

	private  static final  Log LOG = LogFactory.getLog(StringUtil.class);

	// ~ Methods
	// ================================================================

	/**
	 *
	 * @param password password
	 * @param algorithm algorithm
	 * @return String
	 * @throws Exception 编译异常
	 */
	public static String encodePassword(String password, String algorithm) throws Exception {
		byte[] unencodedPassword = password.getBytes("UTF-8");

		MessageDigest md = null;

		try {
			// first create an instance, given the provider
			md = MessageDigest.getInstance(algorithm);
		} catch (Exception e) {
			LOG.error("Exception: " + e);

			return password;
		}

		md.reset();

		// call the update method one or more times
		// (useful when you don't know the size of your data, eg. stream)
		md.update(unencodedPassword);

		// now calculate the hash
		byte[] encodedPassword = md.digest();

		StringBuffer buf = new StringBuffer();

		for (int i = 0; i < encodedPassword.length; i++) {
			if ((encodedPassword[i] & 0xff) < 0x10) {
				buf.append("0");
			}

			buf.append(Long.toString(encodedPassword[i] & 0xff, 16));
		}

		return buf.toString();
	}

	/**
	 * check if a string is null or empty
	 *
	 * @param str str
	 * @return boolean
	 */
	public static boolean isNullEmp(String str) {
		// 2007.1.15 by Ryu Pan
		// if(str == null || str.length()==0){
		if (StringUtils.isEmpty(str)) {
			return true;
		}
			return false;

	}

	/**
	 * check if a string is null or empty
	 *
	 * @param str str
	 * @return boolean
	 */
	public static boolean isNullEmpTrim(String str) {

		if (StringUtils.isEmpty(str)) {
			return true;
		}
			return false;

	}

	/**
	 * @param str str
	 * @return static
	 */
	public static String null2Empty(String str) {
		if (str == null) {
			return "";
		} else {
			return str;
		}
	}

	/**
	 * @param date date
	 * @return String
	 */
	public static String null2Empty(Date date) {
		if (date == null) {
			return "";
		} else {
			return date.toString();
		}

	}

	/**
	 *
	 * @param var var
	 * @return String
	 */
	public static String null2Empty(Long var) {
		if (var == null) {
			return "";
		} else {
			return var.toString();
		}

	}

	/**
	 *
	 * @param var var
	 * @return String
	 */
	public static String null2Empty(BigInteger var) {
		if (var == null) {
			return "";
		} else {
			return var.toString();
		}
	}

	/**
	 *
	 * @param var var
	 * @return String
	 */
	public static String null2Empty(Integer var) {
		if (var == null) {
			return "";
		} else {
			return var.toString();
		}

	}

	/**
	 *
	 * @param str str
	 * @return String
	 */
	public static String empty2Null(String str) {
		if (str == null || str.trim().length() == 0) {
			return null;
		} else {
			return str;
		}

	}

	/**
	 *
	 * @param str str
	 * @return int
	 */
	public static int utf8ByteSize(String str) {
		if (str == null) {
			return 0;
		} else {
			try {
				return str.getBytes("UTF-8").length;
			} catch (UnsupportedEncodingException e) {
				return 0;
			}
		}
	}

	/**
	 *
	 * @param obj obj
	 * @return convertCurrency
	 */
	public static String convertCurrency(Object obj) {
		try {
			NumberFormat nf = new DecimalFormat("0.00");
			return nf.format(obj);
		} catch (Exception e) {
			return "";
		}

	}

	/**
	 *
	 * @param matrixId16 matrixId16
	 * @param cardNo cardNo
	 * @return String
	 */
	public static String generateSdiInPeer(String matrixId16, int cardNo){
		String pre = "53444920";
		String cardNoHex = Integer.toHexString(cardNo);
		while (cardNoHex.length() < 8) {
			cardNoHex = "0" + cardNoHex;
		}
		String suf = Long.toHexString(Long.parseLong(pre + cardNoHex));
		while (suf.length() < 16) {
			suf = "0" + suf;
		}
		return matrixId16 + suf;
	}


	/**
	 *
	 * @param s s
	 * @return String
	 */
	public static String MD5(String s) {
		char [] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			byte[] btInput = s.getBytes("UTF-8");
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘要
			mdInst.update(btInput);
			// 获得密文
			byte[] md = mdInst.digest();
			// 把密文转换成十六进制的字符串形式
			int j = md.length;
			char  [] str = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			log.error("msg:{},e:{}",e.getMessage(),e);
			return null;
		}
	}

	/**
	 *
	 * @param sender sender
	 * @param recipient recipient
	 * @return long
	 */
	public static long getEventId(String sender, String recipient) {
        if (sender.startsWith("0x")) {
         sender = sender.substring(2);
        }
        if (recipient.startsWith("0x")) {
         recipient = recipient.substring(2);
        }
        if (recipient.length() > 12) {
         recipient = recipient.substring(recipient.length() - 12);
        }
        long now = System.currentTimeMillis();
        String nowBinary = Long.toBinaryString(now);
        return (Long.parseLong(recipient, 16) & 0xFFFF) | Long.parseLong(nowBinary.substring(nowBinary.length() - 32), 2) << 16 | ((Long.parseLong(sender, 16) & 0xFFFF) << 48);
   }
}